<?php

namespace plugins\message_push\model;
/**
 * 个推模板发送
 */
class GeTui
{
    /**
     * 小程序模板发送
     */
    public function send_getui($param)
    {
        //根据公司id查询
        $getui_config = db('getui_config')->where('company_id', $param['company_id'])->find();
        if (empty($getui_config)) {
            return api_json_echo(false, '请先配置个推信息');
        }

        $appid = $getui_config['appid'];
        $appkey = $getui_config['appkey'];
        $AppSecret = $getui_config['app_secret'];
        $MasterSecret = $getui_config['master_secret'];
        $url = 'https://restapi.getui.com/v2/' . $appid . '/push/single/cid';
        $str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $key = "";
        for ($i = 0; $i < 32; $i++) {
            $key .= $str{mt_rand(0, 32)};    //生成32位随机数
        }
        $title = $param['title'];
        $content = $param['content'];
        $arr['request_id'] = $key;
        $arr['settings'] = ["ttl" => 3600000];
        $arr['audience'] = ['cid' => $param['cid']];
        $json_arr = ['title' => $title, 'content' => $content];
        $arr['push_message'] = ['transmission' => json_encode($json_arr)];
        $arr['push_channel']['ios'] = [
            "type" => "notify",
            'aps' => [
                'alert' => ['title' => $title, 'body' => $content],
                'content-available' => 0,
                'sound' => 'default'
            ]
            // 'auto_badge'=>'+1'
        ];
        $arr['push_channel']['android'] = [
            'ups' => [
                'notification' => [
                    'title' => $title,
                    'body' => $content,
                    'click_type' => 'none'
                ],
            ]
        ];
        $token = $this->get_ts_token($appid, $appkey, $MasterSecret,$param['company_id']);
        if (!$token) {
            return false;
        }
        $json = json_encode($arr);
        return $this->http_post_json($url, $json, $token);
    }

    public function get_ts_token($appid, $appkey, $MasterSecret,$company_id)
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        $getui_config = db('getui_config')->where('company_id', $company_id)->find();
        if ($getui_config['expire_time'] < $msectime) {
            $url = 'https://restapi.getui.com/v2/' . $appid . '/auth';
            $sign = hash("sha256", $appkey . $msectime . $MasterSecret);
            $json = json_encode(['sign' => $sign, 'timestamp' => $msectime, 'appkey' => $appkey]);
            $res = $this->http_post_json($url, $json);
            $resarr = json_decode($res[1], true);
            if ($resarr['msg'] == 'success') {
                db('getui_config')->where('id', $getui_config['id'])->update(['token' => $resarr['data']['token'], 'expire_time' => $resarr['data']['expire_time']]);
            } else {
                return false;
            }
            return $resarr['data']['token'];
        }

        return $getui_config['token'];
    }

    function http_post_json($url, $jsonStr, $token = '')
    {
        $arr = array('Content-Type: application/json; charset=utf-8');
        if (!empty($token)) {
            $arr[1] = 'token: ' . $token;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $arr);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return array($httpCode, json_decode($response,true));

    }

}